<template>
  <div class="user-commission-records">
    <!-- 佣金统计区域 -->
    <div class="commission-summary">
      <div class="summary-card total">
        <div class="summary-icon">
          <i class="fas fa-coins"></i>
        </div>
        <div class="summary-content">
          <div class="summary-label">总佣金金额</div>
          <div class="summary-value">{{ formatCurrency(totalAmount) }} USDT</div>
        </div>
      </div>
      <div class="summary-card settled">
        <div class="summary-icon">
          <i class="fas fa-check-circle"></i>
        </div>
        <div class="summary-content">
          <div class="summary-label">已结算金额</div>
          <div class="summary-value">{{ formatCurrency(settledAmount) }} USDT</div>
        </div>
      </div>
      <div class="summary-card pending">
        <div class="summary-icon">
          <i class="fas fa-clock"></i>
        </div>
        <div class="summary-content">
          <div class="summary-label">待结算金额</div>
          <div class="summary-value">{{ formatCurrency(pendingAmount) }} USDT</div>
        </div>
      </div>
    </div>
    
    <!-- 筛选区域 -->
    <div class="filters-container">
      <div class="date-filter">
        <span class="filter-label">日期范围：</span>
        <div class="date-inputs">
          <input 
            type="date" 
            v-model="filters.startDate" 
            @change="handleFilterChange"
            class="date-input"
            :max="today"
          />
          <span class="date-separator">至</span>
          <input 
            type="date" 
            v-model="filters.endDate" 
            @change="handleFilterChange"
            class="date-input"
            :max="today"
          />
        </div>
      </div>
      <div class="status-filter">
        <span class="filter-label">结算状态：</span>
        <select v-model="filters.status" @change="handleFilterChange" class="status-select">
          <option value="">全部</option>
          <option value="待结算">待结算</option>
          <option value="可提现">可提现</option>
          <option value="已提现">已提现</option>
        </select>
      </div>
      <button class="reset-button" @click="resetFilters">重置筛选</button>
    </div>

    <!-- 表格区域 -->
    <div class="commission-table-container">
      <table class="commission-table">
        <thead>
          <tr>
            <th>记录ID</th>
            <th>产生时间</th>
            <th>关联订单</th>
            <th>佣金金额</th>
            <th>结算状态</th>
            <th>结算时间</th>
          </tr>
        </thead>
        <tbody v-if="filteredRecords.length > 0">
          <tr v-for="record in paginatedRecords" :key="record.id">
            <td class="record-id">{{ record.id }}</td>
            <td>{{ formatDate(record.createdAt) }}</td>
            <td class="order-info">
              <div class="order-id">{{ record.orderId }}</div>
              <div class="order-summary" :title="record.productSummary">{{ record.productSummary }}</div>
            </td>
            <td class="amount">{{ formatCurrency(record.amount) }} USDT</td>
            <td>
              <span class="status-tag" :class="getStatusClass(record.status)">
                {{ record.status }}
              </span>
            </td>
            <td>{{ record.settlementDate ? formatDate(record.settlementDate) : '-' }}</td>
          </tr>
        </tbody>
        <tbody v-else>
          <tr>
            <td colspan="6" class="no-data">
              暂无佣金记录数据
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination" v-if="filteredRecords.length > 0">
      <button 
        class="page-button" 
        :disabled="currentPage === 1" 
        @click="currentPage--"
      >
        上一页
      </button>
      <span class="page-info">
        {{ currentPage }} / {{ totalPages }}
      </span>
      <button 
        class="page-button" 
        :disabled="currentPage === totalPages" 
        @click="currentPage++"
      >
        下一页
      </button>
      <span class="total-info">
        共 {{ filteredRecords.length }} 条记录
      </span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue';
import { generateUserCommissionData } from '@/utils/adminMock';

const props = defineProps({
  userId: {
    type: String,
    required: true
  }
});

// 状态变量
const commissionRecords = ref<any[]>([]);
const loading = ref(true);
const currentPage = ref(1);
const pageSize = ref(10);
const today = new Date().toISOString().split('T')[0]; // 今天的日期，用于日期选择器的最大值

// 筛选条件
const filters = ref({
  startDate: '',
  endDate: '',
  status: ''
});

// 监听用户ID变化，重新加载数据
watch(() => props.userId, () => {
  loadCommissionData();
});

// 初始化时加载数据
onMounted(() => {
  loadCommissionData();
});

// 加载佣金数据
const loadCommissionData = () => {
  loading.value = true;
  
  try {
    // 生成模拟数据
    const data = generateUserCommissionData(props.userId, 30);
    commissionRecords.value = data;
    
    // 重置分页
    currentPage.value = 1;
  } catch (error) {
    console.error('加载佣金数据失败:', error);
  } finally {
    loading.value = false;
  }
};

// 处理筛选条件变化
const handleFilterChange = () => {
  currentPage.value = 1; // 重置为第一页
};

// 重置筛选条件
const resetFilters = () => {
  filters.value = {
    startDate: '',
    endDate: '',
    status: ''
  };
  currentPage.value = 1;
};

// 根据筛选条件过滤记录
const filteredRecords = computed(() => {
  return commissionRecords.value.filter(record => {
    let matchesStartDate = true;
    let matchesEndDate = true;
    let matchesStatus = true;

    // 处理开始日期筛选
    if (filters.value.startDate) {
      const startDate = new Date(filters.value.startDate);
      startDate.setHours(0, 0, 0, 0);
      matchesStartDate = new Date(record.createdAt) >= startDate;
    }

    // 处理结束日期筛选
    if (filters.value.endDate) {
      const endDate = new Date(filters.value.endDate);
      endDate.setHours(23, 59, 59, 999);
      matchesEndDate = new Date(record.createdAt) <= endDate;
    }

    // 处理状态筛选
    if (filters.value.status) {
      matchesStatus = record.status === filters.value.status;
    }

    return matchesStartDate && matchesEndDate && matchesStatus;
  });
});

// 计算总佣金金额
const totalAmount = computed(() => {
  return filteredRecords.value.reduce((sum, record) => sum + record.amount, 0);
});

// 计算已结算金额
const settledAmount = computed(() => {
  return filteredRecords.value
    .filter(record => record.status === '已提现')
    .reduce((sum, record) => sum + record.amount, 0);
});

// 计算待结算金额
const pendingAmount = computed(() => {
  return filteredRecords.value
    .filter(record => record.status === '待结算' || record.status === '可提现')
    .reduce((sum, record) => sum + record.amount, 0);
});

// 计算总页数
const totalPages = computed(() => {
  return Math.max(1, Math.ceil(filteredRecords.value.length / pageSize.value));
});

// 当前页的记录
const paginatedRecords = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredRecords.value.slice(start, end);
});

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

// 格式化货币
const formatCurrency = (value: number) => {
  return value.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  });
};

// 获取状态标签的CSS类
const getStatusClass = (status: string) => {
  switch (status) {
    case '已提现':
      return 'status-settled';
    case '可提现':
      return 'status-withdrawable';
    case '待结算':
      return 'status-pending';
    default:
      return '';
  }
};
</script>

<style lang="scss" scoped>
.user-commission-records {
  width: 100%;
  margin-bottom: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

// 佣金统计区域
.commission-summary {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  padding: 16px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #eaeaea;
  
  .summary-card {
    display: flex;
    align-items: center;
    padding: 16px;
    border-radius: 8px;
    background-color: #fff;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    
    .summary-icon {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 48px;
      height: 48px;
      border-radius: 50%;
      margin-right: 16px;
      color: #fff;
      font-size: 20px;
    }
    
    .summary-content {
      flex: 1;
      
      .summary-label {
        font-size: 14px;
        color: #606266;
        margin-bottom: 4px;
      }
      
      .summary-value {
        font-size: 20px;
        font-weight: 600;
        color: #303133;
      }
    }
    
    &.total .summary-icon {
      background-color: #409eff;
    }
    
    &.settled .summary-icon {
      background-color: #67c23a;
    }
    
    &.pending .summary-icon {
      background-color: #e6a23c;
    }
  }
}

// 筛选区域
.filters-container {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  padding: 16px;
  background-color: #f9f9f9;
  border-bottom: 1px solid #eaeaea;
}

.date-filter, .status-filter {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-label {
  font-size: 14px;
  color: #606266;
  white-space: nowrap;
}

.date-inputs {
  display: flex;
  align-items: center;
  gap: 8px;
}

.date-input {
  padding: 6px 10px;
  font-size: 14px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  outline: none;
  transition: border-color 0.2s;
  
  &:focus {
    border-color: #409eff;
  }
}

.date-separator {
  color: #909399;
}

.status-select {
  padding: 6px 10px;
  font-size: 14px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  outline: none;
  background-color: #fff;
  transition: border-color 0.2s;
  
  &:focus {
    border-color: #409eff;
  }
}

.reset-button {
  padding: 6px 15px;
  font-size: 14px;
  color: #606266;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  
  &:hover {
    color: #409eff;
    border-color: #c6e2ff;
    background-color: #ecf5ff;
  }
}

// 表格区域
.commission-table-container {
  overflow-x: auto;
}

.commission-table {
  width: 100%;
  border-collapse: collapse;
  
  th, td {
    padding: 12px 15px;
    text-align: left;
    border-bottom: 1px solid #ebeef5;
  }
  
  th {
    font-weight: 600;
    color: #606266;
    background-color: #f5f7fa;
  }
  
  tbody tr {
    transition: background-color 0.3s;
    
    &:hover {
      background-color: #f5f7fa;
    }
  }
  
  .record-id {
    font-family: monospace;
    color: #606266;
  }
  
  .order-info {
    .order-id {
      font-family: monospace;
      font-weight: 500;
      color: #409eff;
      margin-bottom: 4px;
    }
    
    .order-summary {
      font-size: 12px;
      color: #909399;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      max-width: 200px;
    }
  }
  
  .amount {
    font-weight: 600;
    color: #67c23a;
    text-align: right;
  }
}

// 状态标签
.status-tag {
  display: inline-block;
  padding: 2px 8px;
  font-size: 12px;
  border-radius: 4px;
  
  &.status-settled {
    color: #67c23a;
    background-color: #f0f9eb;
  }
  
  &.status-withdrawable {
    color: #409eff;
    background-color: #ecf5ff;
  }
  
  &.status-pending {
    color: #e6a23c;
    background-color: #fdf6ec;
  }
}

// 分页区域
.pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  padding: 16px;
  border-top: 1px solid #ebeef5;
}

.page-button {
  padding: 6px 12px;
  font-size: 14px;
  color: #606266;
  background-color: #f4f4f5;
  border: 1px solid #d3d4d6;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  
  &:hover:not(:disabled) {
    color: #409eff;
    border-color: #c6e2ff;
    background-color: #ecf5ff;
  }
  
  &:disabled {
    color: #c0c4cc;
    cursor: not-allowed;
  }
}

.page-info {
  font-size: 14px;
  color: #606266;
}

.total-info {
  margin-left: 16px;
  font-size: 14px;
  color: #909399;
}

.no-data {
  padding: 30px;
  text-align: center;
  color: #909399;
}

// 响应式设计
@media (max-width: 768px) {
  .commission-summary {
    grid-template-columns: 1fr;
  }
  
  .filters-container {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .date-filter, .status-filter {
    width: 100%;
  }
  
  .commission-table th:nth-child(1),
  .commission-table td:nth-child(1),
  .commission-table th:nth-child(6),
  .commission-table td:nth-child(6) {
    display: none;
  }
}
</style> 